<template>
  <el-card>
    <div class="mb-20">
      <el-input placeholder="角色名称" v-model="username" style="width: 85%; margin-right: 10px;"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="searchHandler" >查询</el-button>
      <el-button @click="reset" >清空</el-button>
    </div>
    <div class="mb-20">
      <el-button type="primary" @click="addHandler" >添加</el-button>
      <el-button type="danger" @click="batchRemove" >批量删除</el-button>
    </div>
    <el-table class="mb-20" 
      :data="userList" 
      style="width: 100%" 
      @selection-change="handleSelectionChange" 
      border 
      empty-text="暂无数据"
      :stripe="true"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center" width="150"></el-table-column>
      <el-table-column prop="nickName" label="用户昵称" align="center"></el-table-column>
      <el-table-column prop="roleName" label="角色列表" align="center"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="200" >
        <template slot-scope="{ row }">
          <el-button type="info"    size="mini" icon="el-icon-info" @click="toAssign(row)" ></el-button>
          <el-button type="primary" size="mini" icon="el-icon-edit-outline" @click="edit(row)" ></el-button>
          <el-popconfirm :title="`确定要删除 ${ row.username } 吗`" class="ml-10" @onConfirm="handleDeleteRow(row)" >
            <el-button type="danger"  size="mini" icon="el-icon-delete" slot="reference"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="userForm.id ? '修改用户' : '添加用户'" :visible.sync="editDialogVisible" top="0" >
      <el-form :model="userForm" label-width="100px" >
        <el-form-item label="用户名">
          <el-input style="width: 600px;" size="small" v-model="userForm.username" ></el-input>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input style="width: 600px;" size="small" v-model="userForm.nickName" ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" v-if="!userForm.id" >
          <el-input style="width: 600px;" size="small" v-model="userForm.password" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelHandler">取 消</el-button>
        <el-button type="primary" @click="saveHandler">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置角色" :visible.sync="addDialogVisible" top="0" >
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input style="width: 600px;" size="small" disabled :value="userForm.username" ></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="checkedList"  @change="handleCheckedChange">
            <el-checkbox v-for="role in roleList" :label="role.roleName" :key="role.id">{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total">
    </el-pagination>
  </el-card>
</template>

<script>
import { user, remove, update, getRolesList, doAssign, save, batchRemove } from '@/api/user'
import { Message } from 'element-ui'
import Lodash from 'lodash'
export default {
  name: 'User',
  data() {
    return {
      page: 1,
      limit: 5,
      total: 0,
      username: '',
      searchname: '',
      userList: [],
      userForm: {},
      editDialogVisible: false,
      addDialogVisible: false,
      checkAll: false,
      isIndeterminate: true,
      checkedList: [],
      roleList: [],
      loading: false,
      deleteSelection: []
    }
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      this.loading = true
      try {
        let result = await user(this.page, this.limit, this.searchname)
        this.total = result.total
        this.userList = result.items
        this.loading = false
      } catch (error) {
        this.loading = false
        console.error(error)
      }
    },
    // 多选
    handleSelectionChange(val) {
      this.deleteSelection = val;
    },
    // 切换展示数
    handleSizeChange(val) {
      this.limit = val
      this.getUserList();
    },
    // 翻页
    handleCurrentChange(val) {
      this.page = val
      this.getUserList();
    },
    // 查看
    async toAssign(row) {
      this.addDialogVisible = true
      this.userForm = row
      try {
        let result = await getRolesList(row.id);
        this.roleList = result.allRolesList
        this.checkedList = result.assignRoles.map(item => item.roleName)
      } catch (error) {
        console.error(error)
      }
    },
    // 查看全选操作
    handleCheckAllChange(val) {
      this.checkAll = val
      this.checkedList = val ? this.roleList : []
      this.isIndeterminate = false
    },
    // 查看单选操作
    handleCheckedChange(value) {
      let checkCount = this.checkedList.length
      this.checkAll = checkCount == this.roleList.length
      this.isIndeterminate = checkCount < this.roleList.length && checkCount > 0 
    },
    // 查看取消
    cancel() {
      this.addDialogVisible = false
    },
    // 查看保存
    async save() {
      this.addDialogVisible = false
      let userId = this.userForm.id
      let roleId = this.roleList.filter(item => {
        return this.checkedList.includes(item.roleName)
      }).map(role => role.id).join()
      try {
        await doAssign(userId, roleId)
        this.getUserList();
        Message.success('分配角色成功')
      } catch (error) {
        Message.error('分配角色失败')
        console.error(error)
      }
    },
    // 编辑
    edit(row) {
      this.editDialogVisible = true
      this.userForm = Lodash.cloneDeep(row)
    },
    // 编辑取消
    cancelHandler() {
      this.editDialogVisible = false
    },
    // 编辑保存
    async saveHandler() {
      this.editDialogVisible = false
      console.log(this.userForm)
      try {
        if(this.userForm.id) {
          await update(this.userForm)
          Message.success('修改成功')
        } else {
          await save(this.userForm)
          Message.success('添加成功')
        }
        this.getUserList();
      } catch (error) {
        console.error(error)
        if(this.userForm.id) {
          Message.error('修改失败')
        } else {
          Message.error('添加失败')
        }
      }
    },
    // 删除
    async handleDeleteRow(row) {
      try {
        await remove(Number(row.id))
        this.getUserList();
        Message.success('删除成功')
      } catch (error) {
        console.error(error)
        Message.error('删除失败')
      }
    },
    addHandler() {
      this.editDialogVisible = true
      this.userForm = {
        username: '',
        nickName: '',
        password: ''
      }
    },
    searchHandler() {
      this.searchname = this.username
      this.getUserList();
    },
    reset() {
      this.username = ''
      this.searchname = ''
      this.getUserList();
    },
    async batchRemove() {
      let userIdList = this.deleteSelection.map(item => item.id)
      try {
        await this.$confirm('确定删除吗', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          async callback(action) {
            if(action == 'cancel' || action == 'close' ) {
              Message.info('取消删除')
            } else {
              await batchRemove(userIdList)
              this.getUserList()
            }
          }
        })
      } catch (error) {
        console.error(error)
      }
    },
  },
  mounted() {
    this.getUserList();
  }
}
</script>

<style>

</style>